package org.bintrotter.apeer.receivestates;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import org.bintrotter.apeer.Peer;

public class Bitfield implements ReceiveState {

	private Peer m_peer;
	private byte[] buffer;
	private SocketChannel 	sc;
	private ByteBuffer 		bb;

	public Bitfield(Peer peer) {

		m_peer = peer;
		bb = null;
	}
	
	@Override
	public void reset() {
		
		sc = m_peer.channel();
		
		int payloadLen = ((MessageLength)m_peer.get(States.LENGTH)).length()-1;
		
		buffer = new byte[payloadLen];
		bb	= ByteBuffer.wrap(buffer);
	}

	@Override
	public States update()  {

		try {

			sc.read(bb);
			
			if(bb.hasRemaining() == false) {
				
				m_peer.inBitfield(buffer);
				return States.LENGTH;
			}
			
		} catch (Exception e) {
			
			return States.SHUTDOWN;
		}
		
		return States.BITFIELD;
	}
}
